//
//  SYDownloadFile.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/5/27.
//  Copyright © 2019年 SanYi. All rights reserved.
//

#import "SYDownloadFile.h"

@implementation SYDownloadFile

/**
 *  @author Jakey
 *
 *  @brief  下载文件
 *
 *  @param requestURL 请求地址
 *  @param success    下载成功回调
 *  @param failure    下载失败回调
 *  @param progress   实时下载进度回调
 */
+ (void)downloadFileWithUrl:(NSString*)requestURL
                    success:(void (^)( id responseObject))success
                    failure:(void (^)(NSError *error))failure
                   progress:(void (^)(float progress ,long long bytesRead))progress
                   savePath:(NSString *)filePath
{
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:requestURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL * url = [NSURL fileURLWithPath:filePath];
        
        return url;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if(!error){
            success(nil);
        }else{
            failure(error);
        }
    }];
    
    [manager setDownloadTaskDidWriteDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDownloadTask * _Nonnull downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
      //  NSLog(@"bytesWritten = %lld",bytesWritten);
        
      //  NSLog(@"download：%f", (float)totalBytesWritten / totalBytesExpectedToWrite);
        
        float p = (float)totalBytesWritten / totalBytesExpectedToWrite;
        progress(p ,bytesWritten);
    }];
    
    
    [downloadTask resume];
}

@end
